package com.example.zyl.common.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
public class ThreadPoolConfig implements AsyncConfigurer {


    /**
     * 线程池配置
     * 适用于异步定时任务处理
     * @return ThreadPoolTaskExecutor
     */
    @Bean
    @Qualifier("threadScheduledExecutor")
    public ThreadPoolTaskExecutor threadScheduledExecutor() {

        ThreadPoolTaskExecutor executor = getTaskExecutor();
        // 线程名前缀
        executor.setThreadNamePrefix("scheduled-pool-");
        return getTaskExecutor();
    }


    /**
     * 线程池配置
     * 适用于异步任务处理
     * @return ThreadPoolTaskExecutor
     */
    @Bean(name = "threadAsyncExecutor")
    public ThreadPoolTaskExecutor threadAsyncExecutor() {

        ThreadPoolTaskExecutor executor = getTaskExecutor();
        // 线程名前缀
        executor.setThreadNamePrefix("async-pool-");
        return executor;
    }


    private static ThreadPoolTaskExecutor getTaskExecutor() {
        // 获取处理器核心数
        int processors = Runtime.getRuntime().availableProcessors();
        // 创建线程池
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(processors);
        // 最大线程数
        executor.setMaxPoolSize(processors * 2);
        // 队列容量
        executor.setQueueCapacity(300);
        // 等待任务完成再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 初始化线程池
        executor.initialize();
        return executor;
    }
}
